//
//  ImportantAreaDetailViewController.m
//  Utils
//
//  Created by enghou on 2018/6/13.
//  Copyright © 2018年 xyxorigation. All rights reserved.
//

#import "ImportantAreaDetailViewController.h"
#import "SelectedButton.h"
#import "XXTextView.h"
#import "FileItemModel.h"
#import "NetWorkerManager.h"
#import "UIViewController+ChooseInfoViewController.h"
#import <TZImagePickerController.h>
#import "PropertyDictItemModel.h"
@interface ImportantAreaDetailViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *photoImageView;
@property (weak, nonatomic) IBOutlet UITextField *importantAreaNameField;
@property (weak, nonatomic) IBOutlet UITextField *importantAreaCategoryField;
@property (weak, nonatomic) IBOutlet UITextField *importantAreaAddressField;
@property (weak, nonatomic) IBOutlet UITextField *belongingPolicField;
@property (weak, nonatomic) IBOutlet UITextField *manipulatorNameField;
@property (weak, nonatomic) IBOutlet UITextField *manipulatorPhoneField;
@property (weak, nonatomic) IBOutlet UITextField *manipulatorMobileField;
@property (weak, nonatomic) IBOutlet UITextField *concerndField;
@property (weak, nonatomic) IBOutlet SelectedButton *yesBtn;
@property (weak, nonatomic) IBOutlet SelectedButton *noBtn;
@property (weak, nonatomic) IBOutlet XXTextView *noteField;
@property (weak, nonatomic) IBOutlet UILabel *noteLabel;


@property(nonatomic,strong)NSString *filePath;
@property(nonatomic,strong)NSArray *categoryArray;
@property(nonatomic,strong)PropertyDictItemModel *selectedCategoryModel;

@property(nonatomic,strong)NSArray *concernedLevelArray;
@property(nonatomic,strong)PropertyDictItemModel *selectedConcernedModel;
@end

@implementation ImportantAreaDetailViewController
-(instancetype)init{
    UIStoryboard *story = [UIStoryboard storyboardWithName:@"ImportantAreaDetail" bundle:[NSBundle mainBundle]];
    return [story instantiateViewControllerWithIdentifier:@"ImportantAreaDetailViewController"];
}
- (IBAction)yesAction:(UIButton *)sender {
    sender.selected = YES;
    self.noBtn.selected = NO;
    self.noteLabel.text = @"隐患描述";
}
- (IBAction)noAction:(UIButton *)sender {
    sender.selected = YES;
    self.yesBtn.selected = NO;
    self.noteLabel.text = @"备注";
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

#pragma UITextField Delegate

- (IBAction)checkingIfExists:(UITextField *)sender {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    NSString *orgId = self.orgId;
    NSString *areaId = self.ids;
    if (orgId.length > 0) {
        param[@"importantArea.organization.id"] = orgId;
    }
    if (areaId.length > 0) {
        param[@"importantArea.id"] = areaId;
    }
    param[@"importantArea.name"] = sender.text;
    [[NetWorkerManager sharedInstance]postWithPath:@"/mobile/comprehensiveGovernance/importantArea/hasImportantArea.action" parameter:param completeBlock:^(NSDictionary *source) {
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source];
        if (model.success) {
            BOOL data = [source[@"data"] boolValue];
            if (data) {
                sender.text = @"";
            }
        }
    } failBlock:^(NSInteger code) {
        
    }];
}

-(void)selectImage{
    TZImagePickerController *picker = [[TZImagePickerController alloc]initWithMaxImagesCount:1 delegate:nil];
    picker.didFinishPickingPhotosHandle = ^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.photoImageView.image = photos[0];
    };
    [self presentVC:picker];
}

-(void)selectCategory{
    [self commonAlertWithContent:@"区域类别" choosenBlock:^(PropertyDictItemModel *model) {
        self.selectedCategoryModel = model;
        self.importantAreaCategoryField.text = model.displayName;
    } getList:^(NSArray *array) {
        self.categoryArray = array;
    }];
}

-(void)selectConcernedLevel{
    [self commonAlertWithContent:@"关注程度" choosenBlock:^(PropertyDictItemModel *model) {
        self.selectedConcernedModel = model;
        self.concerndField.text = model.displayName;
    } getList:^(NSArray *array) {
        self.concernedLevelArray = array;
    }];
}

-(void)uploadFiles:(NSArray <NSData *>*)files successBlock:(void(^)(NSArray <FileItemModel *>*))suc{
    [self beginLoading];
    [[NetWorkerManager sharedInstance]uploadImageWithPath:kUploadFilePath parameter:nil files:files fileName:@"file" suffix:@"jpg" completeBlock:^(NSDictionary *source) {
        [self endLoading];
        BaseModel *model = [[BaseModel alloc]initWithSourceDict:source listItemClass:[FileItemModel class]];
        if (model.success) {
            if (suc) {
                suc(model.list);
            }
        }else{
            [self alertSome:model.msg];
        }
    } failBlock:^(NSInteger code) {
        [self endLoading];
        [self alertSome:kNetWorkFail];
    }];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.row) {
        case 0:
            [self selectImage];
            break;
        case 2:
            [self selectCategory];
            break;
        case 8:
            [self selectConcernedLevel];
            break;
        default:
            break;
    }
}


#pragma mark - 获取详情
-(NSString *)detailPath{
    return @"/mobile/comprehensiveGovernance/importantArea/getImportantAreaById.action";
}

-(NSDictionary *)detailParam{
    return @{@"id":self.ids};
}

-(void(^)(NSDictionary *))configView{
    void(^config)(NSDictionary *) = ^(NSDictionary *source){
        NSDictionary *data = source[@"data"];
        [self.photoImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",ServerPath,data[@"imgUrl"]]] placeholderImage:[UIImage imageNamed:@"img_enterprise"]];
        self.importantAreaNameField.text = data[@"name"];
        self.selectedCategoryModel = [[PropertyDictItemModel alloc]init];
        self.selectedCategoryModel.ids = data[@"organization"][@"orgType"][@"id"];
        self.importantAreaCategoryField.text = data[@"organization"][@"orgType"][@"displayName"];
        self.importantAreaAddressField.text = data[@"address"];
        self.belongingPolicField.text = data[@"nativePolice"];
        self.manipulatorNameField.text = data[@"leader"];
        self.manipulatorPhoneField.text = data[@"telephone"];
        self.manipulatorMobileField.text = data[@"mobile"];
        self.selectedConcernedModel = [[PropertyDictItemModel alloc]init];
        self.selectedConcernedModel.ids = data[@"attentionExtent"][@"id"];
        self.concerndField.text = data[@"attentionExtent"][@"displayName"];
        BOOL hasDanger = [data[@"hasDanger"] boolValue];
        if (hasDanger) {
            self.yesBtn.selected = YES;
            self.noBtn.selected = NO;
            self.noteLabel.text = @"隐患描述";
            self.noteField.text = data[@"dangerDes"];
        }else{
            self.yesBtn.selected = NO;
            self.noBtn.selected = YES;
            self.noteLabel.text = @"备注";
            self.noteField.text = data[@"remark"];
        }
    };
    return config;
}

#pragma 更新记录
-(NSString *)updatePath{
    return @"/mobile/comprehensiveGovernance/importantArea/updateImportantArea.action";
}

-(NSDictionary *)updateParameter{
    NSMutableDictionary *param = [[self addedParameter]mutableCopy];
    param[@"importantArea.id"] = self.ids;
    return param;
}

//新增记录
-(NSString *)addPath{
    return @"/mobile/comprehensiveGovernance/importantArea/addImportantArea.action";
}

-(void)updateRecord{
    if (self.photoImageView.image) {
        NSData *data = UIImageJPEGRepresentation(self.photoImageView.image, 0.1);
        [self uploadFiles:@[data] successBlock:^(NSArray<FileItemModel *> *array) {
            FileItemModel *model = array[0];
            self.filePath = model.path;
            [super updateRecord ];
        }];
    }else{
        [super addRecord];
    }
}

-(NSDictionary *)addedParameter{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    if (self.orgId.length > 0) {
        param[@"importantArea.organization.id"] = self.orgId;
    }
    if ([self.filePath length] > 0) {
        param[@"file.path"] = self.filePath;
    }
    if (self.importantAreaNameField.text.length == 0) {
        [self alertSome:@"请输入重点区域名称!"];
        return nil;
    }
    param[@"importantArea.name"] = self.importantAreaNameField.text;
    if ([self.selectedCategoryModel.ids length] == 0) {
        [self alertSome:@"请选择区域类型"];
        return nil;
    }
    param[@"importantArea.type.id"] = self.selectedCategoryModel.ids;
    param[@"importantArea.address"] = self.importantAreaAddressField.text;
    if (self.belongingPolicField.text.length == 0) {
        [self alertSome:@"请选择所属派出所!"];
        return nil;
    }
    param[@"importantArea.nativePolice"] = self.belongingPolicField.text;
    param[@"importantArea.leader"] = self.manipulatorNameField.text;
    param[@"importantArea.telephone"] = self.manipulatorPhoneField.text;
    param[@"importantArea.mobile"] = self.manipulatorMobileField.text;
    if (self.selectedConcernedModel.ids.length > 0) {
        param[@"importantArea.attentionExtent.id"] = self.selectedConcernedModel.ids;
    }
    if (self.yesBtn.selected) {
        param[@"importantArea.hasDanger"] = @"true";
        param[@"importantArea.dangerDes"] = self.noteField.text;
    }else{
        param[@"importantArea.hasDanger"] = @"false";
        param[@"importantArea.remark"] = self.noteField.text;
    }
    return param;
}

-(void)addRecord{
    if (self.photoImageView.image) {
        NSData *data = UIImageJPEGRepresentation(self.photoImageView.image, 0.1);
        [self uploadFiles:@[data] successBlock:^(NSArray<FileItemModel *> *array) {
            FileItemModel *model = array[0];
            self.filePath = model.path;
            [super addRecord];
        }];
    }else{
        [super addRecord];
    }
}

//删除记录
-(NSString *)delPath{
    return @"/mobile/comprehensiveGovernance/importantArea/deleteImportantAreaById.action";
}

-(NSDictionary *)delParameter{
    return @{@"id":self.ids};
}

//操作完成后发送的通知
-(NSString *)refresh_not_name{
    return @"refresh_important_area";
}

@end
